package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"mime"
	"net/http"
	"path/filepath"
	"time"
)

const endpoint = "117.27.231.246:9000"
const accessKeyID = "EoSYgm5gu5P9BQdIXzsp"
const secretAccessKey = "42ILntEI4eirSTOSQJHy1f7C4nK0eeVomK6SBYtS"
const bucketName = "123"

func Upload(c *gin.Context) {
	fileHeader, _ := c.FormFile("file")
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})
	filePath, fileErr := fileHeader.Open()
	if fileErr != nil {
		log.Fatal(fileErr)
	}

	defLoc, _ := time.LoadLocation("Asia/Shanghai")
	now := time.Now().In(defLoc).Truncate(time.Second)
	timestr := now.Format("20060102150405")
	if err != nil {
		log.Fatal(err)
	}
	ext := filepath.Ext(fileHeader.Filename)
	contentType := mime.TypeByExtension(ext)
	objectName := fmt.Sprintf("%s/%s", timestr, fileHeader.Filename)
	minioClient.PutObject(c, bucketName, objectName, filePath, fileHeader.Size, minio.PutObjectOptions{ContentType: mime.TypeByExtension(contentType)})

	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, objectName)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "upload success",
		"data": map[string]interface{}{
			"originUrl": url,
			"thumbUrl":  url,
		},
	})
}
